package com.lmbsvn.front.service.impl;

import com.lmbsvn.front.repository.Hd_svnauthRepository;
import com.lmbsvn.front.model.Hd_svnauth;
import com.lmbsvn.front.model.Hd_svngroup;
import com.lmbsvn.front.model.Hd_svnproject;
import com.lmbsvn.front.service.Hd_svnauthService;
import com.lmbsvn.front.service.Hd_svngroupService;
import com.lmbsvn.front.service.Hd_svnprojectService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("hd_svnauthServiceImpl")
public class Hd_svnauthServiceImpl implements Hd_svnauthService{

	@Autowired
	private Hd_svnauthRepository svnauthRepository;

	@Autowired
	private Hd_svnprojectService projectService;//项目

	@Autowired
	private Hd_svngroupService groupService;//用户组

	/**
	 * 格式化资源.如果资源没有[],自动加上[relateRoot:/]
	 * @param projectId
	 * @param resources
	 * @return
	 * @throws Exception
	 */
	public String formatResources(String projectId, String resources) throws Exception {
		return this.formatResources(projectService.getSvnproject(projectId), resources);
	}

	/**
	 * 格式化资源.如果资源没有[],自动加上[relateRoot:/]
	 * @param project
	 * @param resources
	 * @return
	 * @throws Exception
	 */
	public String formatResources(Hd_svnproject project, String resources) throws Exception {
		//去除[xxx:]，重新加上[relateRoot:/]，防止跨项目授权
		resources = StringUtils.replaceEach(resources, new String[]{"[","]"}, new String[]{"",""});
		if (resources.indexOf(":")!=-1) {
			resources = StringUtils.substringAfter(resources, ":");
		}
		//如果资源没有[],自动加上
		String relateRoot = projectService.getRelateRootPath(project);
		if(!resources.startsWith("[") && !resources.endsWith("]")){
			if(resources.startsWith("/")){
				return "["+relateRoot+":"+resources+"]";
			}else{
				return  "["+relateRoot+":/"+resources+"]";
			}
		}
		return resources;
	}

	/**
	 * 根据项目ID，加载该项目下每一个资源的授权情况
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
	public Map<String ,List<Hd_svnauth>> getMapByProjectId(String projectId) throws Exception {
		Map<String ,List<Hd_svnauth>> resultMap = new HashMap<String ,List<Hd_svnauth>>();

		//获得项目所有的用户组
		List<Hd_svngroup> groupList = groupService.getListByProjectId(projectId);

		//获得当前项目所有被授权的资源
		List<Map<String, String>> list = svnauthRepository.getResourcesByProjectId(projectId);

		//遍历每一个资源
		for (int i = 0; i < list.size(); i++) {
			String source = list.get(i).get("f_resources").toString();
			List<Hd_svnauth> authList = new ArrayList<Hd_svnauth>();
			for (int j = 0; j < groupList.size(); j++) {
				//遍历所有用户组，查询该资源权限情况
				List<Hd_svnauth> tempList = svnauthRepository.getSvnauthByProjectIdAndGroupidAndResources(projectId, groupList.get(j).getId(), source);
				if(tempList != null && tempList.size() > 0){
					authList.addAll(tempList);
				}
			}
			resultMap.put(source, authList);
		}
		return resultMap;
	}
}
